﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace BingImages
{
    class Minimize
    {
        // ------------ DEBUT INITIALISATION VARIABLES ------------ //
        const int SW_SHOWNORMAL = 1;
        const int SW_MINIMIZE = 6;

        [DllImport("User32.DLL", CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static Thread threadMinimize = null;
        private static Process[] processList = null;
        private static Process processBing = null;
        // ------------ FIN INITIALISATION VARIABLES ------------ //

        public static void setMinimize(string processTitle)
        {
            threadMinimize = new Thread(() => minimizeApp(processTitle));
            threadMinimize.IsBackground = true;
            threadMinimize.Start();
        }

        private static void minimizeApp(string processTitle)
        {
            int time = 0;
            int idprocess = 0;

            while (time < 90)
            {
                clear();

                Thread.Sleep(1000);

                processList = Process.GetProcesses();

                foreach (Process process in processList)
                {
                    // On vérifie si la fenêtre passée en paramètre est ouverte
                    if (process.MainWindowTitle == processTitle)
                    {
                        idprocess = process.Id;

                        processBing = Process.GetProcessById(idprocess);

                        // Minimise la fenêtre
                        ShowWindow(processBing.MainWindowHandle, SW_MINIMIZE);
                    }
                }

                time++;
            }

            clear();
        }

        private static void clear()
        {
            if (processList != null)
            {
                foreach (Process process in processList)
                {
                    process.Dispose();
                }

                processList = null;
            }

            if (processBing != null)
            {
                processBing.Dispose();
                processBing = null;
            }
        }
    }
}
